<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Admin extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Usermodel');
        $this->load->helper('url');
        $this->load->library('myauth');
        // $this->output->enable_profiler(TRUE);
    }

    public function index() {
        $this->user_manage();
    }

    public function user_manage() {
        $data['is_admin'] = $this->myauth->check_permission('p6');
        if ($data['is_admin'] == false) {
            echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
            $url = site_url('login');
            echo "<script language='javascript' >alert('你不是管理员！魂淡!登录去!');location.replace('$url');</script>";
        }
        $data['userinfo'] = $this->Usermodel->user_list();
        $this->load->view('admin.php', $data);
    }

    public function user_create() {
        if (empty($_POST['uname'])) {
            echo 'error_1';
            return;
        }
        if (empty($_POST['upass'])) {
            echo 'error_2';
            return;
        }
        $this->db->select('*')->from('user')->where('uname', $_POST['uname']);
        $ret = $this->db->get(); //查询用户名 
        $ret = $ret->result_array();
        if ($ret) {
            echo 'error_3';
            return;
        }
        $user['uname'] = $_POST['uname'];
        $user['upass'] = $_POST['upass'];
        for ($i = 1; $i <= 7; $i++) {
            $pid = 'p' . $i;
            if (!empty($_POST["$pid"])) {
                $user["$pid"] = '1';
            }
        }
        $this->Usermodel->create_user($user);
        echo 'success';
    }

    public function user_delete() {
        if (empty($_POST['uid'])) {
            echo 'error_1';
            return;
        }
        $this->db->where('uid', $_POST['uid']);
        $this->db->delete('user');
        echo 'success';
    }

    public function user_modify() {
        if (empty($_POST['uid'])) {
            echo 'error_1';
            return;
        }
        if (empty($_POST['upass'])) {
            echo 'error_2';
            return;
        }
        $uid = $_POST['uid'];
        $user['upass'] = $_POST['upass'];
        for ($i = 1; $i <= 7; $i++) {
            $pid = 'p' . $i;
            if (!empty($_POST["$pid"])) {
                $user["$pid"] = '1';
            }else{
                $user["$pid"] = 0;
            }
        }
        $this->Usermodel->modify_user($user, $uid);
        echo 'success';
    }

    public function user_detail() {
        if (empty($_POST['uid'])) {
            echo 'error_1';
            return;
        }
        $ret = $this->Usermodel->user_detail($_POST['uid']);
        $jsonStr = json_encode($ret[0]);
        echo $jsonStr;
    }

}

